
from model import Registration
from dzutil import include
from dzpage import Page
from dzmail import SendMail
import time

class Controller:

    def _register_now_button(self,**args):

        r = Registration(**args)

        errors = r.errors()
        if errors:
            for item in errors:
                warning(item)
        else:
            r.token  = zoomer.session.new_session()  # session module generates unique tokens
            r.expiry = time.time() + 3600  # one hour
            r.put()
            return self.send_registration_confirmation(r.email,r.token)

    def send_registration_confirmation(self,address,token):

        body       = include('activate.txt') % dict(site_name=zoomer.name,activation_link=url_for(action='confirm',token=token))
        returnaddr = 'Registration <%s>' % zoomer.config.get('site','register_email')

        try:
            SendMail(returnaddr,address,'%s registration' % zoomer.name,body,'html')
        except:
            zoomer.log.log('D','Registration error sending %s to %s' % (newsid,webvars.email))
            return Page(include('register_error.txt'))
        else:
            zoomer.log.log('D','Registration sent to %s with token %s' % (address,token))
            return Page(include('step2.txt') % dict(site_name=zoomer.name))

    def _confirm(self,token):
        rlist = Registration.find(token=token)
        if rlist:
            r = rlist[0]

            if r.expired():
                return Page(include('expired.txt') % dict(register_link=url_for(action=zoomer.app.name)))

            elif r.already_registered():
                return Page(include('already_register.txt') % dict(site_name=zoomer.name,site_link=zoomer.site_url))

            elif r.name_taken():
                return Page(include('name_taken.txt'))

            else:
                r.activate()
                return Page(include('register_complete.txt') % dict(site_name=zoomer.name))

result = Controller()